package me.zhengjie.gas.utils;
import org.springframework.jdbc.core.RowMapper;

import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class CamelCaseRowMapper implements  RowMapper<Map<String, Object>> {

	public static String convertToCamelCase(String underscoreName) {
		StringBuilder result = new StringBuilder();
		String[] words = underscoreName.split("_");
		for (int i = 0; i < words.length; i++) {
			String word = words[i];
			if (i == 0) {
				// 将首个单词的首字母小写
				result.append(word.toLowerCase());
			} else {
				// 将后续单词的首字母大写
				result.append(Character.toUpperCase(word.charAt(0)));
				if (word.length() > 1) {
					result.append(word.substring(1).toLowerCase());
				}
			}
		}
		return result.toString();
	}

	@Override
	public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
		ResultSetMetaData metaData = rs.getMetaData();
		int columnCount = metaData.getColumnCount();
		Map<String, Object> map = new HashMap<>(columnCount);
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

		for (int i = 1; i <= columnCount; i++) {
			String columnName = metaData.getColumnName(i);
			columnName = convertToCamelCase(columnName);

			Object value = rs.getObject(i);

			if (value instanceof Timestamp) {
				LocalDateTime localDateTime = ((Timestamp) value).toLocalDateTime();
				map.put(columnName, formatter.format(localDateTime));
			} else if (value instanceof Date) {
				LocalDate localDate = ((Date) value).toLocalDate();
				map.put(columnName, localDate);
			} else if (value instanceof Array) {
				Array array = rs.getArray(i);
				if (array != null) {
					Object[] javaArray = (Object[]) array.getArray();
					map.put(columnName, javaArray);
				} else {
					map.put(columnName, null);
				}
			} else {
				map.put(columnName, value);
			}
		}
		return map;
	}
}